package com.tskj.mh.studyroom.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tskj.mh.studyroom.aop.annotation.SystemControllerLog;
import com.tskj.mh.studyroom.dao.StudyRoomDAO;
import com.tskj.mh.studyroom.utility.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author LeonSu
 */
@Service
public class StudyRoomService {

    //预约开始时间
    private final String START_TIME = "08:00:00";

    //预约结束时间
    private final String END_TIME = "23:59:59";

    @Autowired
    private StudyRoomDAO studyRoomDAO;

    @Autowired
    private StudentService studentService;

    public JSONArray getStudyRoomList() {
        return studyRoomDAO.getStudyRoomList();
    }

    public JSONArray getTimeList(String adUserName, String roomId, String date) {
        JSONArray allList = studyRoomDAO.getTimeAndCountList(roomId, date);
        JSONArray allOrderList = studyRoomDAO.getOrderList(adUserName, date);
        JSONArray retArray = new JSONArray();
        JSONObject data;
        String currentTime = Tools.getNewDateTime();
        Boolean found;
        for (Object obj : allList) {
            JSONObject json = (JSONObject) obj;
            if (String.format("%s %s", date, json.getString("starttime")).compareToIgnoreCase(currentTime) <= 0) {
//            if (json.getString("endtime").compareToIgnoreCase(currentTime) <= 0) {
                continue;
            }

            if (allOrderList.size() > 0) {
                found = false;
                for (Object objOrder : allOrderList) {
                    JSONObject jsonOrder = (JSONObject) objOrder;
                    if (json.getString("starttime").equalsIgnoreCase(jsonOrder.getString("starttime"))) {
                        //如果当前学生已下过订单，则需要把此时间段从列表中排除出去，不允许再预约此时间
                        found = true;
                        break;
                    }
                }
                if (found) {
                    continue;
                }
            }
            data = new JSONObject();
            data.put("id", json.getString("tid"));
            data.put("timeTitle", String.format("%s - %s", Tools.getShortTime(json.getString("starttime")), Tools.getShortTime(json.getString("endtime"))));
            data.put("timeCount", json.getIntValue("bnum"));
            retArray.add(data);
        }
        return retArray;
    }

    /**
     * 判断当前时间是否在可预约的时间范围内
     * @return true：是在时间范围内，false：不在时间范围内
     */
    public boolean isValidSubscribeTime () {
        String time = Tools.getNowTime();
        return (time.compareTo(START_TIME) >= 0 && time.compareTo(END_TIME) <= 0);
    }

    /**
     * 最大允许的订单数
     */
    private final int ORDERCOUNT = 2;

    /**
     * 检查是否允许下订单，一是：8:00-16:00能下，二是如果该用户今天创建的订单数小于2
     * @param userName
     * @return
     */
    public Boolean checkStopTime(String userName) {
        Boolean result;
        String time = Tools.getNowTime();
        if (time.compareTo(START_TIME) < 0 || time.compareTo(END_TIME) > 0) {
            result = false;
        } else {
            result = true;
            if (studyRoomDAO.getOrderByAdUserName(userName, Tools.today()) >= ORDERCOUNT) {
                result = false;
            }
        }
        return result;
    }

    @SystemControllerLog(MODULENAME = "自习室")
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveOrder(JSONObject student, JSONObject data) {
        JSONObject retData = new JSONObject();

        String adUserName = student.getString("username");
        //TODO：保存前，需要检查当前用户是否已有未完成订单
        if (!checkStopTime(adUserName)) {
            retData.put("code", 1);
            retData.put("errMsg", "已创建过订单，请不要重复创建");
            return retData;
        }

        String timeId = data.getString("id");
        String studyRoomName = data.getString("hairCutRoom");
        String studyRoomId = data.getString("hairCutId");
        String newStudyRoomId = studyRoomDAO.getStudyRoomId(studyRoomName);
        if (!newStudyRoomId.equalsIgnoreCase(studyRoomId)) {
            retData.put("code", 1);
            retData.put("errMsg", "数据不正确");
            return retData;
        }
        String dateString = data.getString("date");
        String timeString = data.getString("time");
        String startTime = timeString.split("-")[0].trim();
        String endTime = timeString.split("-")[1].trim();

        String sex = student.getString("sexy");
        int sexId = sex.equals("男") ? 1 : 0;
        String studentName = student.getString("studentname");
        String studentNo = student.getString("studentid");
        String xueYuan = student.getString("xueyuan");
        String roomSortNo = studyRoomDAO.getStudyRoomSortNo(studyRoomId, studyRoomName);
        String timeSortNo = studyRoomDAO.getTimeSortNo(studyRoomId, timeId);
        String maxOrderNo = studyRoomDAO.getMaxOrderNo(studyRoomName, dateString, startTime, endTime);
        String code = String.format("%s-%s-%04d", roomSortNo, timeSortNo, Integer.valueOf(maxOrderNo));

        try {

            //TODO:保存前，需要检查当前时间是否已订满
            if (!studyRoomDAO.canSave(studyRoomName, startTime, endTime, 0, dateString)) {
                retData.put("code", 1);
                retData.put("errMsg", "当前时间已订满，请选择其他时间");
                return retData;
            }
            studyRoomDAO.save(Tools.newId(), studentName, sex, Integer.valueOf(maxOrderNo), studyRoomName, startTime, endTime, 0, code, dateString, adUserName);
            retData.put("code", 0);
            JSONObject detail = new JSONObject();
            retData.put("data", detail);
            student = new JSONObject();
            student.put("name", studentName);
            student.put("no", studentNo);
            student.put("xueyuan", xueYuan);
            student.put("sex", sex);
            detail.put("student", student);

            JSONObject order = new JSONObject();
            order.put("type", 2);
            order.put("address", studyRoomName);
            order.put("date", dateString);
            order.put("time", timeString);
            order.put("code", code);
            detail.put("order", order);
            return retData;
        } catch (Exception e) {
            e.printStackTrace();
            retData.put("code", 1);
            retData.put("errMsg", "自习室订单创建失败，请稍后重试");
            return retData;
        }
    }
}
